package com.lingjtx.common.security.strategy;

import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.ResponseResult;

import java.util.ArrayList;
import java.util.List;

/**
 * token状态委托环境
 */
public class TokenContext {

    private TokenStateHandler state;

    private final List<TokenStateHandler> handlers = new ArrayList<>();

    private ResponseResult<Object> errorResponseResult;

    public ResponseResult<Object> getErrorResponseResult() {
        return errorResponseResult;
    }

    public void setErrorResponseResult(ResponseResult<Object> errorResponseResult) {
        this.errorResponseResult = errorResponseResult;
    }

    public void setHandlers(TokenStateHandler state) {
        state.setContext(this);
        handlers.add(state);
    }

    public TokenStateHandler getState() {
        return state;
    }

    public void setState(TokenStateHandler state) {
        this.state = state;
        this.state.setContext(this);
    }

    public boolean process(RedisOptions redis, String token) {
        for (TokenStateHandler stateHandler: handlers) {
            if (!stateHandler.handler(redis, token)) {
                this.setErrorResponseResult(stateHandler.retError());
                return false;
            }
        }
        return true;
    }
}
